<template>
  <div class="crud-opts">
    <span class="crud-opts-left">
      <!--左侧插槽 -->
      <slot name="left"/>
      <el-button icon="el-icon-plus" v-permission="permission.add==undefined ? ['']:permission.add" @click="crud.toAdd"
                 style="border-radius: 0;color:white;margin-right:10px;height:32px;background:#347DE1 !important"></el-button>
      <img class="img" src="@images/update.png" alt="" @click="doReply()">

      <el-tooltip class="item" effect="dark" content="启动" placement="bottom-start">
        <img class="img" v-permission="permission.start==undefined ? ['']:permission.start"
             src="@images/start.svg" alt="" @click="toStart(crud.selections)"
             :disabled="crud.selections.length == 0">
      </el-tooltip>
      <el-tooltip class="item" effect="dark" content="停用" placement="bottom-start">
        <img class="img" v-permission="permission.stop==undefined ? ['']:permission.stop"
             src="@images/stop.svg" alt="" @click="toStop(crud.selections)"
             :disabled="crud.selections.length == 0">
      </el-tooltip>
      <el-tooltip class="item" effect="dark" content="重启" placement="bottom-start">
        <img class="img" v-permission="permission.restart==undefined ? ['']:permission.restart"
             src="@images/restart.svg" alt="" @click="toRestart(crud.selections)"
             :disabled="crud.selections.length == 0">
      </el-tooltip>
      <el-tooltip class="item" effect="dark" content="发布" placement="bottom-start">
        <img class="img" v-permission="permission.install==undefined ? ['']:permission.install"
             src="@images/release.svg" alt="" @click="toInstall(crud.selections)"
             :disabled="crud.selections.length != 1">
      </el-tooltip>
      <el-button class="btn-height" content="测试连接" icon="el-icon-link" :disabled="crud.selections.length != 1"
                 @click="checkConnect(crud.selections[0])"
                 style="width: 32px; border-radius: 0; border: 1px solid #a7c7f2; margin-right:10px;background: rgb(244 248 253) !important"></el-button>
      <!--更多操作-->
      <el-popover v-if="checkPermission(['dispatch:edit', 'dispatch:del'])"
                  placement="bottom" width="100" style="height: 30px" trigger="click">
        <img class="img" slot="reference" src="@images/more.png" alt="">
        <div>
          <el-row>
            <el-button v-permission="permission.edit==undefined ? ['']:permission.edit" type="text"
                       @click="crud.toEdit(crud.selections[0])" :disabled="crud.selections.length !== 1">修改</el-button>
          </el-row>
          <el-row>
            <el-button v-permission="permission.del==undefined ? ['']:permission.del"
                       :disabled="crud.selections.length == 0"
                       type="text" :loading="crud.delAllLoading"
                       @click="toDelete(crud.selections)">删除</el-button>
          </el-row>
        </div>
      </el-popover>
      <el-popover placement="bottom-end" style="height: 30px" width="150" trigger="click">
        <img class="img" aria-hidden="true" slot="reference" src="@images/gezi.png" alt="">

        <el-checkbox v-model="allColumnsSelected" :indeterminate="allColumnsSelectedIndeterminate"
                     @change="handleCheckAllChange">
          全选
        </el-checkbox>
        <el-checkbox v-for="(item,i) in crud.props.tableColumns" :key="i" v-model="item.visible"
                     @change="handleCheckedTableColumnsChange(item)">
          {{ item.label }}
        </el-checkbox>
      </el-popover>
       <el-button-group style="height:30px">
        <!--查询按钮-->
        <img class="img" src="@images/search.png" @click="toggleSearch()" v-if="crud.props.searchToggle"
             alt="">
        <div style="display: inline-block;display:flex;align-items:center;" class="select">
          <img class="img" style="margin-right:0px !important" v-if="!crud.props.searchToggle"
               src="@images/hidden.png" alt="" @click="toggleSearch()">
          <el-input placeholder="请输入内容" v-model="qryParam" style="width: 300px;" class="input-with-select"
                    @change="paramChange" v-if="!crud.props.searchToggle" clearable>
            <el-select v-model="qryCloum" @change="cloumChange" slot="prepend" filterable placeholder="请选择"
                       style="width: 100px">
              <el-option v-for="(item, i) in crud.queryList" :key="i" :label="item.cloumName"
                         :value="item.cloumValue"></el-option>
            </el-select>
          </el-input>
          <img class="img" v-if="!crud.props.searchToggle" slot="append" src="@images/search.png" alt=""
               @click="doQuery">
        </div>
      </el-button-group>
      <!--右侧-->
      <slot name="right"/>
    </span>
    <el-button-group style="margin-top: 8px;" class="crud-opts-right">
      <el-pagination :page-size.sync="page.size"
                     :total="page.total"
                     :current-page.sync="page.page"
                     :pager-count="5" prev-text=" " next-text=" "
                     style="margin-top: 8px;"
                     layout="prev, pager, next,sizes,total"
                     @size-change="crud.sizeChangeHandler($event)"
                     @current-change="crud.pageChangeHandler"

      />
    </el-button-group>

    <el-dialog :title="title" :visible.sync="centerDialogVisible" width="50%" center :before-close="handleClose">
      <el-table :data="tableData" style="width: 100%">
        <el-table-column prop="agentCode" label="服务编码"/>
        <el-table-column prop="agentName" label="服务名称"/>
        <el-table-column prop="agentHost" label="服务主机"/>
        <el-table-column prop="agentStatus" label="状态">
          <template slot-scope="scope">
            <i class="el-icon-success" v-if="scope.row.status === 1"
               style="color: #42800d;font-size: 16px"></i>
            <i class="el-icon-remove-outline" v-if="scope.row.status === 0"
               style="color: #ADB2B6;font-size: 16px"></i>
            <i class="el-icon-error" v-if="scope.row.status === 2"
               style="color: #ff171d;font-size: 16px"></i>
            <span style="margin-left: 10px">{{ scope.row.agentStatus }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="errorLog" label="失败原因"/>
      </el-table>
    </el-dialog>
    <el-dialog title="选择升级版本号" :visible.sync="upgradeVisible" width="400px" :before-close="handleUpgradeClose">
      <el-form ref="upgradeForm" :model="upgradeForm" :rules="rules" :label-width="formLabelWidth">
        <el-form-item label="版本号" prop="version">
          <el-select v-model="upgradeForm.version" placeholder="请选择升级版本号" style="width: 100%;">
            <el-option v-for="item in this.dict.server_version" :key="item.value" :label="item.label"
                       :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="doUpgrade()">升 级</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import CRUD, {crud, pagination} from '@crud/crud'
import {mapGetters} from 'vuex'
import remoteAgentApi from '@/api/agent/remoteAgent'
import nodeServer from '@/api/system/node'
import bizAgentApi from "@/api/agent/bizAgent";
import checkPermission from '@/utils/permission' // 权限判断函数

export default {
  mixins: [crud(), pagination()],
  props: {
    permission: {
      type: Object,
      default: null
    },
  },
  dicts: ['server_version'],
  data() {
    return {
      allColumnsSelected: true,
      centerDialogVisible: false,
      upgradeVisible: false,
      title: '',
      allColumnsSelectedIndeterminate: false,
      qryParam: '',
      qryCloum: '',
      appType: 'hdrs-agent',
      tableData: [],
      formLabelWidth: '80px',
      upgradeAgentList: [],
      upgradeForm: {
        version: ''
      },
      rules: {
        version: [
          {required: true, message: '请选择版本号', trigger: 'blur'},
        ],
      }
    }
  },
  computed: {
    ...mapGetters([
      'user'
    ])
  },
  created() {
    this.crud.updateProp('searchToggle', true);
  },
  methods: {
    checkPermission,
    toDelete(datas) {
      this.$confirm(`确认删除选中的${datas.length}条数据?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.crud.delAllLoading = true
        if (datas instanceof Array && datas.length > 0) {
          let delDatas = [];
          datas.forEach(val => {
            if (val.agentStatus != '1' && val.agentStatus != '2') {
              delDatas.push(val);
            }
          })
          if (delDatas.length > 0) {
            if (delDatas[0].hasOwnProperty('id')) {
              this.crud.doDelete(delDatas)
            } else {
              this.crud.doDeleteByPkId(delDatas)
            }
          } else {
            this.crud.delAllLoading = false
            this.crud.notify('选择的所有数据都不允许删除！', CRUD.NOTIFICATION_TYPE.WARNING);
          }
        }
      }).catch(() => {
      })
    },
    toStart(datas) {
      if (datas.length > 0) {
        this.$confirm(`确认【启动】选中的${datas.length}条AGENT吗?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.centerDialogVisible = true;
          this.title = "批量启动调度服务";
          this.tableData = []
          datas.forEach(val => {
            let dataInfo = {
              agentCode: val.agentCode,
              agentName: val.agentName,
              agentHost: val.agentIp,
              agentStatus: '正在启动...',
              status: 0,
              errorLog: ''
            }
            this.tableData.push(dataInfo);
            let dataForm = {
              appType: this.appType,
              agentHost: val.agentIp,
              agentPort: val.agentPort,
              agentCode: val.agentCode,
              agentName: val.agentName,
              version: val.serverVer
            }
            remoteAgentApi.start(dataForm).then(res => {
              if ("200" === res.code) {
                dataInfo.agentStatus = '启动成功'
                dataInfo.status = 1
                this.crud.notify(val.agentName + '启动成功！', CRUD.NOTIFICATION_TYPE.SUCCESS);
              } else {
                dataInfo.agentStatus = '启动失败'
                dataInfo.status = 2
                dataInfo.errorLog = res.msg
                this.crud.notify(val.agentName + '启动失败！', CRUD.NOTIFICATION_TYPE.ERROR);
              }
            }).catch(() => {
            })
          })
        }).catch(() => {
        })
      } else {
        this.crud.notify('请至少选择一个AGENT', CRUD.NOTIFICATION_TYPE.WARNING)
      }

    },
    toStop(datas) {
      if (datas.length > 0) {
        this.$confirm(`确认【停用】选中的${datas.length}条AGENT吗?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.centerDialogVisible = true;
          this.title = "批量停用调度服务";
          this.tableData = []
          datas.forEach(val => {
            let dataInfo = {
              agentCode: val.agentCode,
              agentName: val.agentName,
              agentHost: val.agentIp,
              agentStatus: '正在停用...',
              status: 0,
              errorLog: ''
            }
            this.tableData.push(dataInfo);
            let dataForm = {
              appType: this.appType,
              agentHost: val.agentIp,
              agentPort: val.agentPort,
              agentCode: val.agentCode,
              agentName: val.agentName,
              version: val.serverVer
            }
            remoteAgentApi.stop(dataForm).then(res => {
              if ("200" === res.code) {
                dataInfo.agentStatus = '停用成功'
                dataInfo.status = 1
                this.crud.notify(val.agentName + '停用成功！', CRUD.NOTIFICATION_TYPE.SUCCESS);
              } else {
                dataInfo.agentStatus = '停用失败'
                dataInfo.status = 2
                dataInfo.errorLog = res.msg
                this.crud.notify(val.agentName + '停用失败！', CRUD.NOTIFICATION_TYPE.ERROR);
              }
            }).catch(() => {
            })
          })
        }).catch(() => {
        })
      } else {
        this.crud.notify('请至少选择一个AGENT', CRUD.NOTIFICATION_TYPE.WARNING)
      }
    },
    toRestart(datas) {
      if (datas.length > 0) {
        this.$confirm(`确认【重启】选中的${datas.length}条AGENT吗?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.centerDialogVisible = true;
          this.title = "批量重启调度服务";
          this.tableData = []
          datas.forEach(val => {
            let dataInfo = {
              agentCode: val.agentCode,
              agentName: val.agentName,
              agentHost: val.agentIp,
              agentStatus: '正在重启...',
              status: 0,
              errorLog: ''
            }
            this.tableData.push(dataInfo);
            let dataForm = {
              appType: this.appType,
              agentHost: val.agentIp,
              agentPort: val.agentPort,
              agentCode: val.agentCode,
              agentName: val.agentName,
              version: val.serverVer
            }
            remoteAgentApi.restart(dataForm).then(res => {
              if ("200" === res.code) {
                dataInfo.agentStatus = '重启成功'
                dataInfo.status = 1
                this.crud.notify(val.agentName + '重启成功！', CRUD.NOTIFICATION_TYPE.SUCCESS);
              } else {
                dataInfo.agentStatus = '重启失败'
                dataInfo.status = 2
                dataInfo.errorLog = res.msg
                this.crud.notify(val.agentName + '重启失败！', CRUD.NOTIFICATION_TYPE.ERROR);
              }
            }).catch(() => {
            })
          })
        }).catch(() => {
        })
      } else {
        this.crud.notify('请至少选择一个AGENT', CRUD.NOTIFICATION_TYPE.WARNING)
      }
    },
    toInstall(datas) {
      if (datas.length === 1) {
        let data = datas[0];
        if (data.agentStatus === '0' || data.agentStatus === '3') {
          this.$confirm("确认自动化发布【" + data.agentName + "】吗?", '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            const loading = this.$loading({
              lock: true,
              text: '拼命发布中......',
              spinner: 'el-icon-loading',
              background: 'rgba(0, 0, 0, 0.7)'
            });
            const dataForm = {
              appType: this.appType,
              agentHost: data.agentIp,
              agentPort: data.agentPort,
              agentCode: data.agentCode,
              agentName: data.agentName,
              version: data.serverVer
            }
            remoteAgentApi.install(dataForm).then(res => {
              loading.close();
              this.doReply();
              if ("200" === res.code) {
                this.crud.notify('发布成功!', CRUD.NOTIFICATION_TYPE.SUCCESS);
              } else {
                this.crud.notify('发布失败，原因: ' + res.msg, CRUD.NOTIFICATION_TYPE.ERROR);
              }
            }).catch(() => {
              loading.close();
            })
          }).catch(() => {
          })
        } else {
          this.crud.notify('该AGENT已发布！', CRUD.NOTIFICATION_TYPE.WARNING)
        }
      } else {
        this.crud.notify('只支持单个AGENT的自动化发布', CRUD.NOTIFICATION_TYPE.WARNING)
      }
    },
    toRestore(datas) {
      if (datas.length > 0) {
        this.$confirm(`确认【回滚】选中的${datas.length}条AGENT版本吗?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.centerDialogVisible = true;
          this.title = "批量回滚调度服务版本";
          this.tableData = []
          datas.forEach(val => {
            let dataInfo = {
              agentCode: val.agentCode,
              agentName: val.agentName,
              agentHost: val.agentIp,
              agentStatus: '正在恢复...',
              status: 0,
              errorLog: ''
            }
            this.tableData.push(dataInfo);
            let dataForm = {
              appType: this.appType,
              agentHost: val.agentIp,
              agentPort: val.agentPort,
              agentCode: val.agentCode,
              agentName: val.agentName,
              version: val.serverVer
            }
            remoteAgentApi.restore(dataForm).then(res => {
              if ("200" === res.code) {
                dataInfo.agentStatus = '恢复成功'
                dataInfo.status = 1
                this.crud.notify(val.agentName + '恢复成功！', CRUD.NOTIFICATION_TYPE.SUCCESS);
              } else {
                dataInfo.agentStatus = '恢复失败'
                dataInfo.status = 2
                dataInfo.errorLog = res.msg
                this.crud.notify(val.agentName + '恢复失败！', CRUD.NOTIFICATION_TYPE.ERROR);
              }
            }).catch(() => {
            })
          })
        }).catch(() => {
        })
      } else {
        this.crud.notify('请至少选择一个AGENT', CRUD.NOTIFICATION_TYPE.WARNING)
      }
    },
    doUpgrade() {
      this.$refs['upgradeForm'].validate((valid) => {
        if (valid) {
          this.centerDialogVisible = true;
          this.title = "批量重启调度服务";
          this.tableData = []
          this.upgradeAgentList.forEach(val => {
            let dataInfo = {
              agentCode: val.agentCode,
              agentName: val.agentName,
              agentHost: val.agentIp,
              agentStatus: '正在升级...',
              status: 0
            }
            this.tableData.push(dataInfo);
            let upgradeModel = {newVersion: this.upgradeForm.version}
            let dataForm = {
              appType: this.appType,
              agentHost: val.agentIp,
              agentPort: val.agentPort,
              agentCode: val.agentCode,
              agentName: val.agentName,
              version: val.serverVer,
              dataMap: upgradeModel
            }
            remoteAgentApi.upgrade(dataForm).then(res => {
              if ("200" === res.code) {
                dataInfo.agentStatus = '升级成功'
                dataInfo.status = 1
                this.crud.notify(val.agentName + '升级成功！', CRUD.NOTIFICATION_TYPE.SUCCESS);
              } else {
                dataInfo.agentStatus = '升级失败'
                dataInfo.status = 2
                this.crud.notify(val.agentName + '升级失败！', CRUD.NOTIFICATION_TYPE.ERROR);
              }
            }).catch(() => {
              dataInfo.agentStatus = '升级失败'
              dataInfo.status = 2
            })
          })
        }
      })
    },
    toUpgrade(datas) {
      this.upgradeVisible = true;
      this.upgradeAgentList = datas;
    },
    handleCheckAllChange(val) {
      if (val === false) {
        this.$message({
          message: '请至少选择一列',
          type: 'warning'
        });
        this.allColumnsSelected = true
        return
      }
      for (const key in this.crud.props.tableColumns) {
        this.crud.props.tableColumns[key].visible = val
      }
      this.allColumnsSelected = val
      this.allColumnsSelectedIndeterminate = false
    },
    handleCheckedTableColumnsChange(item) {
      let totalCount = 0
      let selectedCount = 0
      for (const key in this.crud.props.tableColumns) {
        ++totalCount
        selectedCount += this.crud.props.tableColumns[key].visible ? 1 : 0
      }
      if (selectedCount === 0) {
        this.crud.notify('请至少选择一列', CRUD.NOTIFICATION_TYPE.WARNING)
        this.$nextTick(function () {
          item.visible = true
        })
        return
      }
      this.allColumnsSelected = selectedCount === totalCount
      this.allColumnsSelectedIndeterminate = selectedCount !== totalCount && selectedCount !== 0
    },
    toggleSearch() {
      this.crud.props.searchToggle = !this.crud.props.searchToggle
      if (this.crud.props.searchToggle) {
        delete this.crud.query[this.qryCloum];
      }
    },
    paramChange(value) {
      this.qryParam = value;
    },
    cloumChange(value) {
      this.qryCloum = value;
      for (let key in this.crud.query) {
        if (key != this.qryCloum) {
          delete this.crud.query[key]
        }
      }
    },
    doReply() {
      this.crud.findVM('presenter').$refs['table'].clearFilter()
      this.crud.query = {}
      this.qryParam = ''
      this.qryCloum = ''
      this.crud.page.page = 1
      this.crud.params = {}
      this.crud.toQuery()
    },
    doQuery() {
      var key = "";
      var value = "";
      if (this.qryCloum == null || this.qryCloum == '') {
        this.$message({
          message: '请先选择搜索项',
          type: 'warning'
        });
        return;
      }
      if (this.qryCloum != null && this.qryCloum != '') {
        key = this.qryCloum;
      }
      if (this.qryParam != '' && this.qryParam != null) {
        value = this.qryParam;
      }
      this.crud.query[key] = value;
      this.crud.toQuery();
    },
    checkConnect(data) {
      if (data.agentStatus === '1') {
        const loading = this.$loading({
          lock: true,
          text: '正在连接，请稍等...',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        });
        nodeServer.checkConnect(data).then(res => {
          if (res && "SUCCESS" === res) {
            this.$notify({title: '成功', message: '连接成功!', type: 'success'})
          } else {
            this.$notify.error({
              title: '错误',
              message: '连接失败，服务没有启动或节点IP、端口错误！'
            });
          }
          loading.close();
        }).catch(() => {
          loading.close();
        })
      } else {
        this.$notify.error({
          title: '提示',
          message: '该服务未发布或未启动！'
        });
      }
    },
    getStatus(data) {
      if (data.agentStatus === '1') {
        const loading = this.$loading({
          lock: true,
          text: '正在连接，请稍等...',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        });
        let dataForm = {
          appType: this.appType,
          agentHost: data.agentIp,
          agentPort: data.agentPort,
          agentCode: data.agentCode,
          agentName: data.agentName,
          version: data.serverVer
        }
        bizAgentApi.getStatus(dataForm).then(res => {
          if ("200" === res.code) {
            this.crud.notify('获取成功！【' + data.agentName + "】的状态为：" + res.rsd, CRUD.NOTIFICATION_TYPE.SUCCESS);
          } else {
            this.crud.notify('获取失败，失败原因: ' + res.msg, CRUD.NOTIFICATION_TYPE.ERROR);
          }
          loading.close();
        }).catch((error) => {
          loading.close();
        })
      } else {
        this.$notify.error({
          title: '提示',
          message: '该服务未发布或未启动！'
        });
      }
    },
    toRelevance(data) {

    },
    handleClose(done) {
      this.$confirm('确认关闭吗？关闭后将无法批量查看远程操作的结果。')
        .then(_ => {
          this.upgradeVisible = false;
          this.upgradeAgentList = [];
          this.upgradeForm.version = null;
          this.crud.toQuery()
          done();
        })
        .catch(_ => {
        });
    },
    handleUpgradeClose(done) {
      this.$confirm('确认关闭吗？')
        .then(_ => {
          this.upgradeVisible = false;
          this.upgradeAgentList = [];
          this.upgradeForm.version = null;
          this.crud.toQuery()
          done();
        })
        .catch(_ => {
        });
    }
  }
}
</script>

<style>
.crud-opts {
  padding: 6px 0;
  display: -webkit-flex;
  display: flex;
  align-items: center;
}

.crud-opts .crud-opts-right {
  margin-left: auto;
}

.btn-height .el-icon-link {
  font-size: 21px;
  position: relative;
  right: 10px;
  bottom: 4px;
  color: #4488e3;
  font-weight: 600;
}
</style>
